<template>
  <div class="search-suggest">
    <SearchSuggestItem
      v-for="(item, index) in songs"
      :key="index"
      :item="item"
      :keywords="keywords"
      @changeKeyWord="$emit('changeKeyWord', $event)"
    />
  </div>
</template>

<script>
import SearchSuggestItem from "@/components/basics/SearchSuggestItem.vue";
export default {
  name: "SearchSuggest",
  data() {
    return {
      songs: [],
    };
  },

  // 获取搜索建议
  async created() {
    // 确保关键词存在且不为空
    if (!this.keywords || this.keywords.trim() === "") {
      this.songs = [];
      return;
    }
    const res = await this.axios({
      url: "/search/suggest",
      params: { keywords: this.keywords, type: "mobile" },
    });

    const { allMatch: songs } = res.data.result || { allMatch: [] };
    // 获取关键词的第一个字符（去除空格后）
    const firstChar = this.keywords.trim().charAt(0).toLowerCase();

    // 过滤出第一个字符匹配的项
    const filterArr = songs.filter((item) => {
      // 确保keyword存在且不为空
      if (!item.keyword) return false;

      // 比较第一个字符（忽略大小写）
      return item.keyword.trim().charAt(0).toLowerCase() === firstChar;
    });

    console.log("过滤后的结果:", filterArr);
    this.songs = filterArr;

    console.error("获取搜索建议失败:", error);
    this.songs = [];
  },
  props: {
    keywords: String,
  },
  components: {
    SearchSuggestItem,
  },
  watch: {
    // TODO 搜索高亮匹配
    keywords(n) {},
  },
};
</script>

<style scoped>
.search-suggest {
  padding: 10px;
}
</style>
